library(ggplot2)
library(grid)

# gridExtra::grid.arrange()
library(gridExtra)
p1<-ggplot(df, aes(x=SOD,y=tau)) + 
  geom_point() #shape=21,color="black",fill="red",size=3,stroke=0.1

p2<-ggplot(df, aes(SOD)) + 
  geom_histogram(bins=30,colour="black",fill="white")

p3<-ggplot(df, aes(x=Class,y=SOD)) + 
  geom_boxplot() 

grid.arrange(p1,p2,p3, ncol = 3, nrow = 1)


# viewport
a <- qplot(date, unemploy, data = economics, geom = "line")
b <- qplot(uempmed, unemploy, data = economics) + geom_smooth(se = F)
c <- qplot(uempmed, unemploy, data = economics, geom = "path")

vp1 <- viewport(width = 1, height = 1, x=0.5, y=0.5)
vp1 <- viewport()
vp2 <- viewport(width = 0.5, height = 0.5, x=0.5, y=0.5)
vp2 <- viewport(width = 0.5, height = 0.5)
vp3 <- viewport(width = unit(2, "cm"), height = unit(3, "cm"))
vp4 <- viewport(x = 1, y = 1, just = c("top", "right"))
vp5 <- viewport(x = 0, y = 0, just = c("bottom", "right"))

# vplayout----
vplayout <- function(x, y)
  viewport(layout.pos.row = x, layout.pos.col = y)

grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
print(a, vp = vplayout(1, 1:2))
print(b, vp = vplayout(2, 1))
print(c, vp = vplayout(2, 2))

# multiplot----
library(Rmisc)

p1 <- ggplot(diamonds, aes(carat)) +
  geom_histogram()

p2 <- ggplot(diamonds, aes(carat)) +
  geom_histogram(aes(y = ..density..))

multiplot(p1, p2, cols = 2)

dev.off()

# Other way ----
chart1 <- ggplot(diamonds, aes(carat, price, colour = cut)) +
  geom_point() +
  theme(legend.position = c(0.9, 0.72), legend.background = element_rect(I(0)))
chart1

vie <- viewport(width = 0.669, height = 0.4, x = 0.7, y = 0.306)

chart2 <- ggplot(diamonds, aes(depth, fill = cut, alpha = 0.2)) +
  geom_density() + xlim(54, 70) +
  theme(axis.text.y = element_text(face = "bold", colour = "black"),
    axis.title.y = element_blank(),
    axis.text.x = element_text(face = "bold", colour = "black"),
    plot.background = element_rect(I(0), linetype = 0),
    panel.background = element_rect(I(0)),
    panel.grid.major = element_line(colour = NA),
    panel.grid.minor = element_line(colour = NA),
    legend.background = element_rect(I(0), linetype = 1),
    legend.position = c(0.85, 0.72))

print(chart2, vp = vie)
